package com.thundersoft.mm.phone.Wifi;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.MimeTypeMap;

import com.thundersoft.mm.FileTransfer;
import com.thundersoft.mm.phone.ConnectionManager;

import org.json.JSONObject;

import java.io.File;
import java.util.Collection;
import java.util.Locale;

// rec
// first createGroup
public class WifiP2pGroupOwnerManager implements DirectActionListener{
    private static final String TAG = "arlauncher_Wifi";
    private WifiP2pManager wifiP2pManager;

    private WifiP2pManager.Channel channel;

    private BroadcastReceiver broadcastReceiver;

    private Context mContext;

    boolean hasInit = false;

    public void init(Context context){
        if (hasInit){
            if (ConnectionManager.btTextMsgListener!=null && ConnectionManager.mWifiP2pName != null) {
                handler.sendEmptyMessageDelayed(3,100);
                return;
            }
        }

        hasInit = true;
        mContext = context;
        wifiP2pManager = (WifiP2pManager) context.getSystemService(Context.WIFI_P2P_SERVICE);
        channel = wifiP2pManager.initialize(context, context.getMainLooper(), this);
        broadcastReceiver = new DirectBroadcastReceiver(wifiP2pManager, channel, this);
        context.registerReceiver(broadcastReceiver, DirectBroadcastReceiver.getIntentFilter());
        createGroup();
    }

    public void release(){
        if (mContext == null)return;
        mContext.unregisterReceiver(broadcastReceiver);
        removeGroup();
        wifiP2pManager = null;
        channel = null;
        broadcastReceiver = null;
        mContext = null;
        hasInit = false;
        hasConnect = false;
        handler.removeMessages(0);
        handler.removeMessages(1);
        handler.removeMessages(3);
    }

    private Handler handler = new Handler(){
        @Override
        public void dispatchMessage(Message msg) {
            if (msg.what == 0) {
                createGroup();
            }else  if(msg.what == 1){
                removeGroup();
            }else if (msg.what == 3){
                sendP2pName();
            }
        }
    };

    private void createGroup() {
        wifiP2pManager.createGroup(channel, new WifiP2pManager.ActionListener() {
            @Override
            public void onSuccess() {
                Log.e(TAG, "createGroup onSuccess");
            }

            @Override
            public void onFailure(int reason) {
                removeGroup();
                hasConnect = false;
                handler.sendEmptyMessageDelayed(0,500);
                Log.e(TAG, "createGroup onFailure: " + reason);
            }
        });
    }


    private void removeGroup() {
        wifiP2pManager.removeGroup(channel, new WifiP2pManager.ActionListener() {
            @Override
            public void onSuccess() {
                Log.e(TAG, "removeGroup onSuccess");
            }

            @Override
            public void onFailure(int reason) {
                Log.e(TAG, "removeGroup onFailure");
                hasConnect = false;
                handler.sendEmptyMessageDelayed(1,500);
            }
        });
    }



    @Override
    public void onChannelDisconnected() {
        hasConnect = false;
    }

    @Override
    public void wifiP2pEnabled(boolean enabled) {

    }

    boolean hasConnect = false;

    @Override
    public void onConnectionInfoAvailable(WifiP2pInfo wifiP2pInfo) {
        Log.e(TAG, "==================================");
        Log.e(TAG, "onConnectionInfoAvailable "+wifiP2pInfo.groupOwnerAddress);
        Log.e(TAG, "isGroupOwner：" + wifiP2pInfo.isGroupOwner);
        Log.e(TAG, "groupFormed：" + wifiP2pInfo.groupFormed);
        String address = null;
        if(wifiP2pInfo.groupFormed&&wifiP2pInfo.isGroupOwner){
            address = wifiP2pInfo.groupOwnerAddress.getHostAddress().toString();
        }else if(wifiP2pInfo.groupFormed){
            address = wifiP2pInfo.groupOwnerAddress.getHostAddress();
        }
        Log.e(TAG, "address：" + address);
        hasConnect = true;
        Log.e(TAG, "==================================");
    }

    @Override
    public void onDisconnection() {
        hasConnect = false;
    }

    @Override
    public void onSelfDeviceAvailable(WifiP2pDevice wifiP2pDevice) {
        Log.e(TAG, "onSelfDeviceAvailable  "+wifiP2pDevice.deviceName);
        ConnectionManager.mWifiP2pName = wifiP2pDevice.deviceName;
        if (ConnectionManager.btTextMsgListener!=null) {
            sendP2pName();
        }
    }

    private void sendP2pName(){
        try {
            if (!WifiP2pSocket.listening){
                handler.sendEmptyMessageDelayed(3,500);
                return;
            }
            // 开启WIFI p2p
            JSONObject o = new JSONObject();
            o.put("type",String.valueOf(200));
            String name = ConnectionManager.mWifiP2pName;
            o.put("msg",name);
            o.put("port",WifiP2pSocket.listenPort);
            ConnectionManager.btTextMsgListener.sendMsg(o.toString().getBytes());
        }catch (Exception e){
            handler.sendEmptyMessageDelayed(3,500);
        }
    }

    @Override
    public void onPeersAvailable(Collection<WifiP2pDevice> wifiP2pDeviceList) {

    }
}
